package com.shixun.controller;

import com.shixun.dto.AccountDto;
import com.shixun.dto.LoginDto;
import com.shixun.exception.exception.DormException;
import com.shixun.service.AccountService;
import com.shixun.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class StudentLoginController {

    @Autowired
    private AccountService accountService;

    /**
     * 学生账号密码登陆
     * @param loginDto
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody @Validated LoginDto loginDto, HttpSession session){
        String login = accountService.login(loginDto);
        session.setAttribute("student",login);
        return new R(1,"登陆成功", login);
    }

    /**
     * 退出账户
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R logout( HttpSession session){
        session.removeAttribute("student");
        return new R(1,"注销成功",null);
    }

    @PostMapping("updatePassword")
    public R updatePass(@RequestBody @Validated AccountDto accountDto,HttpSession session){
       String sno= (String) session.getAttribute("student");
       if (sno==null){
           throw new DormException("请先登陆");
       }
       return accountService.updatePassword(accountDto,sno);

    }



}
